package top.codef.secure.requesturl.persist;

import static java.util.stream.Collectors.toList;

import java.util.List;
import java.util.Set;

import org.springframework.data.redis.core.StringRedisTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import top.codef.secure.properties.CerberusUrlPersisProperties;
import top.codef.secure.requesturl.RequestUrl;
import top.codef.secure.requesturl.interfaces.RequestUrlPersistHandler;

public class RedisRequestUrlPersisHandler implements RequestUrlPersistHandler {

	private final StringRedisTemplate stringRedisTemplate;

	private final ObjectMapper objectMapper;

	private final CerberusUrlPersisProperties cerberusUrlPersisProperties;

	public RedisRequestUrlPersisHandler(StringRedisTemplate stringRedisTemplate, ObjectMapper objectMapper,
			CerberusUrlPersisProperties cerberusUrlPersisProperties) {
		this.stringRedisTemplate = stringRedisTemplate;
		this.objectMapper = objectMapper;
		this.cerberusUrlPersisProperties = cerberusUrlPersisProperties;
	}

	@Override
	public void save(List<RequestUrl> list) {
		String[] strList = list.stream().map(x -> {
			try {
				return objectMapper.writeValueAsString(x);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			return null;
		}).toArray(String[]::new);
		stringRedisTemplate.boundSetOps(key()).add(strList);
	}

	private String key() {
		return String.format("%s:%s", cerberusUrlPersisProperties.getRedisKeyPrefix(),
				cerberusUrlPersisProperties.getProjectName());
	}

	@Override
	public void clear() {
		stringRedisTemplate.delete(key());
	}

	@Override
	public List<RequestUrl> getCurrentRequestUrl() {
		Set<String> set = stringRedisTemplate.boundSetOps(key()).members();
		List<RequestUrl> list = set.stream().map(x -> {
			try {
				return objectMapper.readValue(x, RequestUrl.class);
			} catch (JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}).collect(toList());
		return list;
	}
}
